/*
 * This project provides a number of implementations for indexing and evaluating
 * <i>Continuous Top-k Queries over Text Streams</i>
 * and has been developped as part of the work described in the article:
 * 
 * Vouzoukidou, N., Amann, B., & Christophides, V. (2012, October). 
 * Processing continuous text queries featuring non-homogeneous scoring functions.
 * In Proceedings of the 21st ACM international conference on Information and 
 * knowledge management (pp. 1065-1074). ACM.
 * http://dl.acm.org/citation.cfm?id=2398404
 * 
 * This software is distributed under the GNU General Public License and as an
 * additional condition of usage, please cite the aforementioned article.
 * 
 * Copyright (C) 2012 ICS/FORTH, Greece and 
 *               2012 LIP6, France
 * 
 * Author: Vouzoukidou Nelly, email: nelly.vouzoukidou (at) gmail (dot) com
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package gr.forth.ics.continuoustopk.index;

import gr.forth.ics.continuoustopk.Item;
import gr.forth.ics.continuoustopk.Constants;
import gr.forth.ics.continuoustopk.Query;
import gr.forth.ics.continuoustopk.Term;
import gr.forth.ics.continuoustopk.metrics.DecayFunction.DecayFunctionType;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import static gr.forth.ics.continuoustopk.Constants.rankingFunction;

/**
 *
 * @author Vouzoukidou Nelly, email: nelly.vouzoukidou (at) gmail (dot) com
 */
public class ConstantAngleOrderingQueryIndex extends AbstractQueryIndex {
    private Map<Term, Set<Query>> map;

    ConstantAngleOrderingQueryIndex() {
        map = new HashMap<Term, Set<Query>>();
    }

    private static Comparator<Query> comparator(final Term term) {
        return new Comparator<Query>() {
            public int compare(Query q1, Query q2) {
                double w1 = q1.minScore() - rankingFunction.beta() * q1.getWeight(term);
                double w2 = q2.minScore() - rankingFunction.beta() * q2.getWeight(term);

                if (w1 > w2) {
                    return 1;
                } else if (w1 < w2) {
                    return -1;
                }
//                System.err.println("q1 (" + q1.getWeight(term) + "): " + q1 + " - q2 (" + q2.getWeight(term) + "): " + q2);
                // equal weights: giving some random ordering (otherwise the two
                // queries would be considered equal by the treemap and one of
                // them would be ignored
                int hash = q1.hashCode() - q2.hashCode();
                if (hash == 0) {
                    if (!q1.equals(q2)) {
                        System.err.println("ERROR in hashCode of queries " + q1 + ", " + q2);
                    }
                }
                return 0;
            }
        };
    }
    
    private final double maxItemScore = rankingFunction.alpha(); // * 1.0

    public void add(Query query) {
        // adding the query only in the term of the highest weight
        for (Term term : query) {
            if (query.getWeight(term) * rankingFunction.beta() < query.minScore() - maxItemScore) {
                continue;
            }
            Set<Query> termSet = map.get(term);
            if (termSet == null) {
                termSet = new TreeSet<Query>(comparator(term));
                map.put(term, termSet);
            }
            termSet.add(query);
        }
    }

    protected void matchItem(Item item) {
        for (Term term : item) {
            Set<Query> queries = map.get(term);
            if (queries == null) {
                continue;
            }
            for (Query query : queries) {
                double score = score(query, item);
                if (shouldUpdate(query, score)) {
                    query.update(item, score);
                    notifyUpdatedListeners(query, item, term, 0);
                }
                //if query is lower than 45 degrees (with cs included)
                if (query.minScore() - rankingFunction.beta() * query.getWeight(term) > rankingFunction.alpha() * item.itemScore()) {
                    break;
                }
                notifyVisitedListeners(query, item, term, 0);
            }
        }
    }

    public Iterable<Query> queries(Term term) {
        return map.get(term);
    }

    @Override
    protected boolean isCompatibleWithDecay() {
        return Constants.decay.type() == DecayFunctionType.noDecay ||
                Constants.decay.type() == DecayFunctionType.linear;
    }

    public void clear() {
        map.clear();
    }

    public Iterator<Term> terms() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public int queryCount(Term term) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
